import cryptoFramework from '@ohos.security.cryptoFramework'
import { DataBlob } from './types'

export enum MdAlg {
  NONE = 0,
  SHA1 = 1,
  SHA224 = 2,
  SHA256 = 3,
  SHA384 = 4,
  SHA512 = 5,
  MD5 = 6,
  SM3 = 7,
}

export class Digest {
  private md: cryptoFramework.Md;

  constructor(alg: MdAlg) {
    this.md = this.createMd(alg);
  }

  digest(input: DataBlob): Promise<DataBlob> {
    return new Promise((resolve, reject) => {
      this.md.update(input)
        .then(() => {
          this.md.digest()
            .then((output) => {
              resolve(output);
            })
            .catch(err => {
              reject(err);
            });
        })
        .catch(err => {
          reject(err);
        });
    });
  }

  getMdLength(): number {
    return this.md.getMdLength();
  }

  getAlgName(alg: MdAlg): string {
    let algName: string = null;
    switch (alg) {
      case MdAlg.SHA1:
        algName = 'SHA1';
        break;
      case MdAlg.SHA224:
        algName = 'SHA224';
        break;
      case MdAlg.SHA256:
        algName = 'SHA256';
        break;
      case MdAlg.SHA384:
        algName = 'SHA384';
        break;
      case MdAlg.SHA512:
        algName = 'SHA512';
        break;
      case MdAlg.MD5:
        algName = 'MD5';
        break;
      case MdAlg.SM3:
        algName = 'SM3';
        break;
    }

    return algName;
  }

  private createMd(alg: MdAlg): cryptoFramework.Md {
    try {
      return cryptoFramework.createMd(this.getAlgName(alg));
    } catch (error) {
      return null;
    }
  }
}